﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Icms.Core;
using Icms.Core.Model;
using Icms.Core.Repository;
using Icms.Resources;

namespace Icms.WebUI.Controllers
{
    public class ParameterCaseKindAjaxDropdownController : Controller
    {
        private readonly IRepo<Parameter> r;

        public ParameterCaseKindAjaxDropdownController(IRepo<Parameter> r)
        {
            this.r = r;
        }

        public ActionResult GetItems(Guid? key, Guid? parent, string code, bool? reqCourt)
        {
            var list = new List<SelectListItem> { new SelectListItem { Text = Mui.not_selected, Value = "" } };
            var result = Enumerable.Empty<Parameter>();
            
            if (parent.HasValue)
            {
                var ck = parent.Value.CaseKind();
                //if economic than civil
                if (ck == 4) ck = 1;
                
                result = r.Where(o => o.Classifier.Code == code && o.Classifier.CaseKind == ck);
                if (reqCourt.HasValue)
                {
                    var court = Globals.Court();
                    var ik = court.CourtType.Code;
                    result = result.Where(o => o.Classifier.InstanceKind.HasValue &&
                                               o.Classifier.InstanceKind.Value == ik);
                }
            }
            
            list.AddRange(result.Select(o => new SelectListItem
                                                 {
                                                     Text = o.Title,
                                                     Value = o.Id.ToString(),
                                                     Selected = o.Id == key
                                                 }));
            return Json(list);
        }
    }
}